package org.zxp.thread.communication.observation;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: zxp-thread-test
 * @description: 中间商  Lock实现版本
 * @author: X-Pacific zhang
 * @create: 2019-05-23 09:56
 **/
public class MidLock {
    static Queue<String> msgqueue = new ConcurrentLinkedQueue<>();
    static Lock lock = new ReentrantLock();
    static Condition dp = lock.newCondition();//生产者的锁
    static Condition cp = lock.newCondition();//消费者的锁

    /**
     * 最多库存10件
     */
    static final int MAX_QUEUE_NUM = 10;
    /**
     * 当前库存件数
     */
    static volatile int num = 0;
    /**
     * 生产者生产消息并提供给中间商
     * 当件数等于10件，则停止生产并通知消费者消费
     * 否则生产
     */
    public static void put(String msg) throws InterruptedException {
        lock.lock();
        try{
            if(num == 10){
                System.out.println("库存满，停止生产！开始消费");
                cp.signalAll();
                dp.await();//停止供货了
            }else{
                msgqueue.add(msg);
                num++;
            }
        }finally {
            lock.unlock();
        }

    }

    /**
     * 消费者消费消息
     *当件数等于   0件，则通知消费者停止消费，并通知生产者生产
     * 否则消费
     */
    public static void take() throws InterruptedException {
        lock.lock();
        try{
            if(num == 0){
                System.out.println("库存空，停止消费！开始生产");
                dp.signalAll();
                cp.await();
            }else{
                num--;
                System.out.println("["+num+"]"+msgqueue.poll()+"真香");
            }
        }finally {
            lock.unlock();
        }
    }

}
